<script lang="ts" setup>
import type { ExtendedModalApi } from '@vben/common-ui';

import { onMounted, ref } from 'vue';

import { useFs } from '@fast-crud/fast-crud';

import { DefTenantConfig } from '#/api';
import { getValidateRulesByFs } from '#/api/common/validateByFs';
import { ActionEnum } from '#/enums/commonEnum';

import { createCrudOptions } from './data/crud';
import BindUserModal from './modules/bind-user-index.vue';
import InitDataModal from './modules/init-data-modal.vue';
import LinkDataSourceDrawer from './modules/link-data-source-drawer.vue';
import ToExamineModal from './modules/to-examine-modal.vue';

defineOptions({
  name: '企业管理',
  inheritAttrs: false,
});
const bindUserRef = ref<ExtendedModalApi>();
const toExamineRef = ref<ExtendedModalApi>();
const initDataRef = ref<ExtendedModalApi>();
const linkDataSourceRef = ref<ExtendedModalApi>();

const { crudRef, crudBinding, crudExpose, appendCrudOptions } = useFs({
  createCrudOptions,
  context: {
    bindUserRef,
    toExamineRef,
    initDataRef,
    linkDataSourceRef,
  },
});

// 页面打开后获取列表数据
onMounted(async () => {
  const addFormOptions = await getValidateRulesByFs({
    Api: DefTenantConfig.Save,
    mode: ActionEnum.ADD,
    customRules: {},
    trigger: 'change',
  });
  const editFormOptions = await getValidateRulesByFs({
    Api: DefTenantConfig.Update,
    mode: ActionEnum.EDIT,
    trigger: 'change',
  });
  appendCrudOptions({ ...addFormOptions, ...editFormOptions });
  crudExpose.doRefresh();
});

function handleSuccess() {
  crudExpose.doRefresh();
}
</script>

<template>
  <FsPage>
    <!-- 租户列表 -->
    <FsCrud ref="crudRef" v-bind="crudBinding" />
    <!-- 绑定租户管理员 -->
    <BindUserModal ref="bindUserRef" />
    <!-- 审核 -->
    <ToExamineModal ref="toExamineRef" @success="handleSuccess" />
    <!-- 初始化表结构和数据 -->
    <InitDataModal ref="initDataRef" @success="handleSuccess" />
    <!-- 初始化租户数据库表结构和初始数据 -->
    <LinkDataSourceDrawer ref="linkDataSourceRef" @success="handleSuccess" />
  </FsPage>
</template>
